/**
 * fui-carousel 借鉴自 NG-ZORRO 0.5.0-rc.2
 *
 */
import {
  Component,
  OnInit,
  OnDestroy,
  ContentChildren,
  HostBinding,
  ElementRef,
  Renderer2,
  Input,
  QueryList,
} from '@angular/core';

import { HostWidthListener } from '../shared/shared';

import { CarouselContentDirective } from './carousel-content.directive';


@Component({
  selector: 'fui-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.sass'],
})
export class CarouselComponent extends HostWidthListener implements OnInit, OnDestroy {
  private activeIndex = 0;
  transform = 'translate3d(0px, 0px, 0px)';
  rendering = false;
  slideContents: QueryList<CarouselContentDirective>;

  @ContentChildren(CarouselContentDirective)
  set _slideContents(value) {
    this.slideContents = value;
    this.renderContent();
  }

  /** Show loading state if set true. */
  @Input() loading = false;

  /** Show bottom dots for navigation. */
  @Input() showDots = true;

  /** Show nav button for navigation. */
  @Input() showNav = true;

  /** Show placeholder when content is empty. */
  @Input() showPlaceholder = false;

  @HostBinding('class.fui-carousel') host = true;
  @HostBinding('class.loading') get loadingClass() {
    return this.loading;
  }

  constructor(
    private hostElement: ElementRef,
    private renderer: Renderer2,
  ) {
    super(hostElement);
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.stopListen();
  }

  onHostWidthChange(width) {
    this.renderContent();
  }

  renderContent() {
    this.rendering = true;
    setTimeout(_ => {
      if (this.slideContents.length > 0) {
        this.setActive(this.activeIndex);
      }

      this.slideContents.forEach((content, i) => {
        content.width = this.hostElement.nativeElement.offsetWidth;
      });

      this.rendering = false;
    });
  }

  setActive(i) {
    this.activeIndex = i;

    this.transform = `translate3d(${-this.activeIndex * this.hostElement.nativeElement.offsetWidth}px, 0px, 0px)`;

    this.slideContents.forEach((slide, idx) => {
      slide.isActive = idx === this.activeIndex;
    });
  }

  get empty() {
    return this.slideContents && this.slideContents.length === 0;
  }

  get needNagivation() {
    return this.slideContents && this.slideContents.length > 1;
  }

  get canNavigateNext() {
    return this.activeIndex + 1 < this.slideContents.length;
  }

  navigateNext() {
    const index = this.activeIndex + 1;
    this.setActive(index);
  }

  get canNavigatePrev() {
    return this.activeIndex > 0;
  }

  navigatePrev() {
    const index = this.activeIndex - 1;
    this.setActive(index);
  }
}
